package org.example.server.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.server.bean.PictureBean;
import org.example.server.common.ResultBean;
import org.example.server.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("picture")
public class PictureController {

    @Autowired
    private PictureService pictureService;

    @RequestMapping("save")
    public ResultBean save(@RequestBody PictureBean pictureBean){
        log.info("/save,图片保存，请求参数为：{}",pictureBean);
        try {
            pictureService.save(pictureBean);
            return new ResultBean(200,"保存成功",null);
        }catch (RuntimeException e){
            return new ResultBean(500,e.getMessage(),null);
        }
    }

    @RequestMapping("list")
    public ResultBean list(){
        log.info("/list,图片列表，无请求参数");
        return new ResultBean(200,"查询成功",pictureService.list());
    }

    @PostMapping("/upload")
    public ResultBean upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        //获取原始名称
        String fileName = multipartFile.getOriginalFilename();
        //组装新名词
        String newName = IdUtil.getSnowflakeNextIdStr()+ fileName.substring(fileName.lastIndexOf("."));
        // 保存图片
        multipartFile.transferTo(new File("D:\\upload\\"+newName));
        String[] strs = {fileName,newName};
        return new ResultBean(200,"上传成功",strs);
    }

    @CrossOrigin("*")
    @RequestMapping("getImage")
    public void getImage(String url, HttpServletResponse response) throws IOException {
        String path = "D:\\upload\\"+url;
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);
        IoUtil.copy(fis,response.getOutputStream());
    }
}
